package com.duowan.cms.parser.util;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.duowan.cms.common.util.DateUtil;
import com.duowan.cms.common.util.Nongli;
import com.duowan.cms.common.util.StringUtil;

/**
 * 解析包工具类
 * @author Ayou
 */
public class Tools {
    
    public String getTime() {
        return DateUtil.format(new Date(), DateUtil.defaultDateTimePatternStr);
    }

    public String getDate() {
        return DateUtil.format(new Date(), DateUtil.defaultDatePatternStr);
    }

    public String getDate(long seconds) {
        Date date = new Date();
        if(seconds>0) date.setTime(seconds);
        return DateUtil.format(date, DateUtil.defaultDatePatternStr);
    }

    public int getDaynum() {
        return (int) (System.currentTimeMillis() / (24 * 60 * 60 * 1000));
    }

    public String replaceAll(String str, String str1, String str2) {
        return str.replaceAll(str1, str2);
    }

    public String parseTime(String datetime, String pattern) {
        try {
            String date = "";
            String time = "";

            if (datetime == null) {
                return "";
            }

            if (datetime.indexOf('.') != -1) {
                datetime = datetime.substring(0, datetime.indexOf('.'));
            }

            if (datetime.indexOf(" ") > 0) {
                String[] datetimelit = datetime.split(" ");
                date = datetimelit[0];
                time = datetimelit[1];
            } else {
                date = datetime;
            }
            String[] datelit = date.split("-");
            if (datelit == null || datelit.length != 3) {
                return datetime;
            }
            pattern = pattern.replaceAll("Y", datelit[0]);
            pattern = pattern.replaceAll("M", datelit[1]);
            pattern = pattern.replaceAll("D", datelit[2]);

            String[] timelit = time.split(":");
            if (timelit == null || timelit.length != 3) {
                return pattern;
            }

            pattern = pattern.replaceAll("h", timelit[0]);
            pattern = pattern.replaceAll("m", timelit[1]);
            pattern = pattern.replaceAll("s", timelit[2]);

            return pattern;
        } catch (Exception e) {
            e.printStackTrace();
            return datetime;
        }
    }

    public int plus(int a, int b) {
        return a + b;
    }

    public int plus(String a, String b) {
        try {
            int ai = Integer.parseInt(a);
            int bi = Integer.parseInt(b);
            return ai + bi;
        } catch (Exception e) {
            return 0;
        }
    }

    public String join(String a, String b) {
        return a + b;
    }

    public String join(String a, String b, String c) {
        return a + b + c;
    }

    public String join(String a, String b, String c, String d) {
        return a + b + c + d;
    }

    public String join(String a, String b, String c, String d, String e) {
        return a + b + c + d + e;
    }

    public String join(String a, String b, String c, String d, String e, String f) {
        return a + b + c + d + e + f;
    }

    public String ruship(String ip) {
        try {
            return ip.substring(0, ip.lastIndexOf(".")) + ".*";
        } catch (Exception e) {
            return "";
        }
    }

    public String ruship(String ip, int startPoint, String appendStr) {
        try {
            return ip.substring(0, ip.indexOf('.', startPoint)) + appendStr;
        } catch (Exception e) {
            return "";
        }
    }

    public String getNongli() {
        try {
            Nongli nl = new Nongli();
            Calendar cld = Calendar.getInstance();
            int year = cld.get(Calendar.YEAR);
            int month = cld.get(Calendar.MONTH) + 1;
            int day = cld.get(Calendar.DAY_OF_MONTH);
            long[] l = nl.calElement(year, month, day);
            String n = "";
            switch ((int) (l[1])) {
            case 1:
                n = "一";
                break;
            case 2:
                n = "二";
                break;
            case 3:
                n = "三";
                break;
            case 4:
                n = "四";
                break;
            case 5:
                n = "五";
                break;
            case 6:
                n = "六";
                break;
            case 7:
                n = "七";
                break;
            case 8:
                n = "八";
                break;
            case 9:
                n = "九";
                break;
            case 10:
                n = "十";
                break;
            case 11:
                n = "十一";
                break;
            case 12:
                n = "十二";
                break;
            }
            return n + "月" + nl.getchina((int) (l[2]));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String getWeekday() {
        return DateUtil.getWeekName();
    }

    public String cutImg(String str) {
        return str.replaceAll("<(IMG|img)[^>]*>", "");
    }

    /**
     * 清除html标签、模板标签
     * @param str
     * @return
     */
    public String cutTags(String str) {
        if(StringUtil.isEmpty(str))
            return "";
        String result = str.replaceAll("<[^>]*>", "");// 清除html标签
        result = result.replaceAll("\\{\\[([^=]+)=([^\\]]+)\\]\\}", "");// 清除模板标签
        return result;
    }

    public int IndexOf(String str1, String str2) {
        if (null != str1 && null != str2)
            return str1.indexOf(str2);
        else
            return -1;
    }

    public int IndexOf(String str1, String str2, int fromIndex) {
        if (null != str1 && null != str2)
            return str1.indexOf(str2, fromIndex);
        else
            return -1;
    }

    public int lastIndexOf(String str1, String str2) {
        return str1.lastIndexOf(str2);
    }

    public String substringEnd(String str, int start, int end) {
        try {
            return str.substring(start, end) + "...";
        } catch (Exception e) {
            return str;
        }
    }

    public String substring(String str, int start) {
        try {
            return str.substring(start);
        } catch (Exception e) {
            return str;
        }
    }

    public String substring(String str, int start, int end) {
        try {
            return str.substring(start, end);
        } catch (Exception e) {
            return str;
        }
    }

    public String substring(String s, String split) {
        int position = s.indexOf(split);
        if (position == -1) {
            return s;
        }
        return s.substring(0, position);
    }

    public String[] split(String str, String lit) {
        return str.split(lit);
    }

    // 截取一段字符，会把不完整的标签干掉
    public static String substring_tag(String s, int len) {
        if (s == null || s.replaceAll("\\s", "").equals("")) {
            return null;
        }
        // 对文章中的特殊语法进行处理
        Pattern pattern = Pattern.compile("\\{\\[([^=]+)=([^\\]]+)\\]\\}", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher match = pattern.matcher(s);
        while (match.find()) {
            s = s.replace(match.group(0), "");
        }
        if (s.length() < len)
            return s;
        try {
            String temp = s.substring(0, len);
            int point1 = temp.lastIndexOf("<");
            int point2 = temp.lastIndexOf(">");
            if (point1 != -1 && point1 > point2) {
                return temp.substring(0, point1);
            }
            return temp;
        } catch (Exception ex) {
            return s;
        }
    }

    // 获取中文格式时间 s必须为 2008-09-12格式
    public String getCNTime(String s) {
        String regexp = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}";
        if (Pattern.matches(regexp, s)) {
            java.sql.Date date = java.sql.Date.valueOf(s);
            SimpleDateFormat myFmt = new SimpleDateFormat("M月d日");
            return myFmt.format(date);
        } else {
            return s;
        }
    }

    public String getMDTime(String s) {
        if (s == null | "".equals(s))
            return "";
        java.sql.Date date = java.sql.Date.valueOf(s);
        SimpleDateFormat myFmt = new SimpleDateFormat("M-dd");
        return myFmt.format(date);
    }

    // 插入字符串
    public static String insert(String s1, String s2, int point) {
        if (StringUtil.isEmpty(s1) || StringUtil.isEmpty(s2) || point > s1.length())
            return s1;
        String temp1 = s1.substring(0, point);
        String temp2 = s1.substring(point);
        return temp1 + s2 + temp2;
    }

    public static int parseInt(String s1) {
        int number = 0;
        try {
            number = Integer.parseInt(s1);
        } catch (Exception e) {
            // TODO: handle exception
            number = 0;
        }
        return number;
    }

    public String encodes(String tag) {
        try {
            tag = URLEncoder.encode(tag, "UTF-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tag;
    }

    public String decodes(String tag) {
        try {
            tag = URLDecoder.decode(tag, "UTF-8");
        } catch (Exception exx) {
            exx.printStackTrace();
        }
        return tag;
    }

    public String trimBlankLine(String content) {
        int index = -1;
        for (int i = 0; i < content.length(); i++) {
            int v = content.charAt(i);
            if (v == 10 || v == 13) {
                index++;
            } else {
                break;
            }
        }
        if (index > -1) {
            content = content.substring(++index);
        }
        return content;
    }

    // 构建一个map
    public Map<String, String> createMap(String keys, String values, String split) {
        Map<String, String> map = new HashMap<String, String>();
        if (keys == null || values == null || "".equals(keys) || "".equals(values))
            return map;
        String[] keyArray = keys.split(split);
        String[] valueArray = values.split(split);
        if (keyArray.length != valueArray.length)
            return map;
        for (int i = 0; i < keyArray.length; i++) {
            map.put(keyArray[i], valueArray[i]);
        }
        return map;
    }
    
    public String getNDateLater(int n){
        return DateUtil.format(DateUtil.getDate(n), DateUtil.defaultDatePatternStr);
    }
    
    public String getNDateBefore(int num){
        return getNDateLater(-num);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new Tools().getNDateBefore(1));
    }

}
